package graphclustering.data;

import graphclustering.util.ClusteringUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LoadandSave {

    public static DWGraph loadGraphFromFile(String fileName) {
        // java.io.InputStreamReader
        BufferedReader fileInput;
        DWGraph graph = new DWGraph();
        try {
            fileInput = new BufferedReader(new FileReader(fileName));
            String nodeSizeStr = fileInput.readLine();
            Integer nodeSize = new Integer(nodeSizeStr);
            graph.nodeSize = nodeSize.intValue();

            graph.graph = new float[graph.nodeSize][graph.nodeSize];

            String nodeIDLine = fileInput.readLine();
            String[] nodeIDArr = nodeIDLine.split(" ", 10000);
            for (int i = 0; i < nodeIDArr.length; i++) {
                graph.nodeIDList.add(nodeIDArr[i]);
            }

            for (int i = 0; i < graph.nodeSize; i++) {
                String oneRowStr = fileInput.readLine();
                String[] rowWeightArr = oneRowStr.split(" ", 10000);
                for (int j = 0; j < graph.nodeSize; j++) {
                    Float weight = new Float(rowWeightArr[j]);
                    graph.graph[i][j] = weight.floatValue();
                }
            }
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {

        }

        return graph;
    }

    public static void saveResultToFile(String fileName, Cluster result) {
        DataOutputStream fileOutput;
        try {
            fileOutput = new DataOutputStream(new FileOutputStream(fileName));
            String resultStr = ClusteringUtils.toString(result);
            fileOutput.writeBytes(resultStr);
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Cluster loadResultFromFile(String fileName) {
        BufferedReader fileInput;
        String resultStr = new String();
        try {
            fileInput = new BufferedReader(new InputStreamReader(
                    new FileInputStream(fileName)));
            resultStr = fileInput.readLine();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ClusteringUtils.parse(resultStr);
    }

}
